import { getCache, getURLParameters, removeCache, setCache, wechatSdkConfig, wxH5Login } from "@/utils";
// import { useCounterStore } from "@/store/user";
// 白名单，这些路由无需验证可直接访问
import { useUserStore } from "@/store/modules/user";
import API_USER from "@/api/user";

// 初始化路由拦截
export async function initRouteInterceptor(pinia: unknown) {
  const userStore = useUserStore();
  
  await userStore.getConfig();
  const token = getCache('token')
  // #ifdef H5
  const href = window.location.href;
  const query = getURLParameters(href);
  const params = href?.split('?')[0];
   // 全局检测vconsole参数并初始化调试工具
  if (query.vconsole === 'show') {
    try {
      const VConsole = await import('vconsole');
      new VConsole.default();
      console.log('vconsole调试模式已全局开启');
    } catch (err) {
      console.error('全局加载vconsole失败:', err);
    }
  }
  if (query.code) {
    await userStore.wetchatLogin(query);
    const url = getCache('redirectUrl')||params;
    setTimeout(() => {
      removeCache('redirectUrl');
      window.location.replace(url);
    }, 0);
  }
  // if(!token&&!query.code){
  //   setCache('redirectUrl', href);
  // }
  // #endif


  if(token) {
    await userStore.setUserInfo();
  }
  // #ifdef H5
  if(token&&query.inviter_code){
    const res =  await API_USER.getBlindInfo();
    if(res.pid0===0){
      if(res.inviter_code_arr.indexOf(query.inviter_code)!==-1){ 
        API_USER.invBlind({inviter_code:query.inviter_code}).then()
      }
    }
  }
  // #endif
}
